package cn.rongcloud.im.ui.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.rongcloud.im.R;
import cn.rongcloud.im.server.network.http.HttpException;
import cn.rongcloud.im.server.response.CommentResponse;
import cn.rongcloud.im.server.response.CreateMomentResponse;
import cn.rongcloud.im.server.response.LikeMomentResponse;
import cn.rongcloud.im.server.response.MomentsListResponse;
import cn.rongcloud.im.server.response.MomentsTypeResponse;
import cn.rongcloud.im.server.response.QiNiuTokenResponse;
import cn.rongcloud.im.server.response.SetPortraitResponse;
import cn.rongcloud.im.server.utils.NToast;
import cn.rongcloud.im.server.utils.photo.PhotoUtils;
import cn.rongcloud.im.server.widget.BottomMenuDialog;
import cn.rongcloud.im.server.widget.LoadDialog;
import io.rong.imageloader.core.ImageLoader;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

/**
 * 邻里圈Activity
 * Created by fangxuegengezou on 2017/3/21.
 */

public class NeighborhoodActivity extends BaseActivity{
    //获取邻里圈分类
    private static final int GET_MOMENTSTYPE_LIST = 5;
    //获取邻里圈动态列表数据
    private static final int GET_MOMENTS_LIST = 6;
    //评论点赞
    private static final int POST_MOMENTS_LIKE = 7;
    //发表评论
    private static final int POST_COMMENT = 8;
    //发布文字邻里圈
    private static final int CREATE_WORD_MOMENT = 9;
    //发布图片邻里圈
    private static final int CREATE_PIC_MOMENT = 10;
    //发布混合邻里圈
    private static final int CREATE_MIX_MOMENT = 11;
//    private static final int UP_LOAD_PORTRAIT = 12;
    private static final int GET_QI_NIU_TOKEN = 13;
    static public final int REQUEST_CODE_ASK_PERMISSIONS = 14;

    LinearLayout ll_headerSelect;
    TextView tv_test;
    List<String> picList;
    private BottomMenuDialog dialog;
    private PhotoUtils photoUtils;
    private UploadManager uploadManager;
    private String imageUrl;
    private Uri selectUri;

    //    SealAction action;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_neighborhood);
        picList= new ArrayList<String>();
        ll_headerSelect = (LinearLayout) findViewById(R.id.ll_headerSelect);
        tv_test = (TextView) findViewById(R.id.tv_test);
        setTitle("邻里圈");
        //获取邻里圈分类
        request(GET_MOMENTSTYPE_LIST, true);
        //获取邻里圈列表数据
        request(GET_MOMENTS_LIST, true);
        //点赞测试
        //request(POST_MOMENTS_LIKE, true);
        //评论测试
        //request(POST_COMMENT, true);
        //发一条邻里圈
//        request(CREATE_MOMENT,true);
        setPortraitChangeListener();

    }
    private void setPortraitChangeListener() {
        photoUtils = new PhotoUtils(new PhotoUtils.OnPhotoResultListener() {
            @Override
            public void onPhotoResult(Uri uri) {
                if (uri != null && !TextUtils.isEmpty(uri.getPath())) {
                    selectUri = uri;
                    LoadDialog.show(mContext);
                    request(GET_QI_NIU_TOKEN);
                }
            }

            @Override
            public void onPhotoCancel() {

            }
        });
    }
    @Override
    public Object doInBackground(int requestCode, String id) throws HttpException {
        switch (requestCode) {
            case GET_MOMENTSTYPE_LIST:
                return action.getMomentstypelist();

            case GET_MOMENTS_LIST:
                return action.getMomentsList(1, "", "1");
            case POST_MOMENTS_LIKE:
                return action.postLikeMomment("699c2cbb97814d51b3999219be81f156");
            case POST_COMMENT:
                return action.postComment("8da31a38ceef48399376ca69568e3379", "骏马是跑出来的，强兵是打出来的。", "");
            case CREATE_PIC_MOMENT:
                return action.createMoment("",picList,"3f22139c1f4e4991b6e5228c7a4bdf58");
            case CREATE_MIX_MOMENT:
                return action.createMoment("宁愿跑起来被拌倒无数次，也不愿规规矩矩走一辈子。就算跌倒也要豪迈的笑。",picList,"3f22139c1f4e4991b6e5228c7a4bdf58");
            case CREATE_WORD_MOMENT:
                return action.createMoment("在我们了解什么是生命之前，我们已将它消磨了一半。",new ArrayList<String>(),"3f22139c1f4e4991b6e5228c7a4bdf58");
            case GET_QI_NIU_TOKEN:
                return action.getQiNiuToken();
        }

        return null;
    }

    @Override
    public void onSuccess(int requestCode, Object result) {
        if (result != null) {
            switch (requestCode) {
                //邻里圈分类
                case GET_MOMENTSTYPE_LIST:
                    MomentsTypeResponse response = (MomentsTypeResponse) result;
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);
                    params.weight = 1;
                    TextView textView1 = new TextView(this);
                    textView1.setLayoutParams(params);
                    textView1.setGravity(Gravity.CENTER);
                    textView1.setText("最新");
                    ll_headerSelect.addView(textView1);
                    for (MomentsTypeResponse.ResultEntity entity : response.getResult()) {
                        String name = entity.getName();
                        TextView textView = new TextView(this);
                        textView.setLayoutParams(params);
                        textView.setGravity(Gravity.CENTER);
                        textView.setText(name);
                        ll_headerSelect.addView(textView);
                    }
                    break;
                case GET_MOMENTS_LIST:
                    MomentsListResponse response1 = (MomentsListResponse) result;
                    String text = "";
                    text += "当前用户呢称:" + response1.getCovertInfo().getNickname() + "\n";
                    System.out.println("用户id:" + response1.getCovertInfo().getUserId());
                    System.out.println("这条邻里圈的id:" + response1.getMoments().get(0).getMomentsInfo().getMomentsId());
                    text += "邻里圈总页数：" + response1.getPageCount() + "\n";

                    text += "当前显示的是第" + response1.getCurPage() + "页" + "\n";
                    text += "邻里圈每页显示10条数据" + "\n";
                    text += "以下是邻里圈内容：" + "\n";
                    text += "=================================" + "\n";

                    for (int i = 0; i < response1.getMoments().size(); i++) {
                        MomentsListResponse.MomentEntity entity = response1.getMoments().get(i);

                        text += "第" + (i + 1) + "条：" + "\n";
                        text += "发送人呢称：" + entity.getUserInfo().getNickname() + "\n";
                        text += "当前这条邻里圈Id:" + entity.getMomentsInfo().getMomentsId() + "\n";
                        String contentType = "";
                        if ("11".equals(entity.getMomentsInfo().getContentType())) {
                            contentType = "图文混合";
                        } else if ("12".equals(entity.getMomentsInfo().getContentType())) {
                            contentType = "纯图片";
                        } else {
                            contentType = "其他（如纯文字）";
                        }
                        text += "邻里圈类型：" + contentType + "\n";
                        text += "邻里圈内容：" + entity.getMomentsInfo().getContent() + "\n";
                        text += "邻里圈标题：" + entity.getMomentsInfo().getTitle() + "\n";
                        text += "邻里圈点赞数：" + entity.getMomentsInfo().getLikeCount() + "\n";
                        text += "点赞的人是：";
                        for (MomentsListResponse.MomentEntity.LikeEntity likeEntity : entity.getLikesInfo()) {
                            text += likeEntity.getLikeUserNick() + " ";
                        }
                        text += "\n";
                        text += "所属社区id:" + entity.getMomentsInfo().getCommunityId() + "\n";
                        text += "MomentsTypeId:" + entity.getMomentsInfo().getMomentsTypeId() + "\n";
                        text += "创建时间：" + entity.getMomentsInfo().getCreateTime() + "\n";
                        text += "评论条数:" + entity.getCommentsInfo().size() + "\n";
                        text += "图片共" + entity.getMediaInfo().getThumbImages().size() + "张" + "\n";
                        text += "缩略图的图片地址为：" + entity.getMomentsInfo().getLinkUrl() + "\n";
                        for (String imageName : entity.getMediaInfo().getThumbImages()) {
                            text += imageName + "  ";
                        }
                        text += "\n";
                        text += "==============================" + "\n";
                    }
                    tv_test.setText(text);
                    break;
                case POST_MOMENTS_LIKE:
                    LikeMomentResponse response2 = (LikeMomentResponse) result;
                    String temp;
                    if ("1".equals(response2.getAction())) {
                        temp = "点赞成功";
                    } else {
                        temp = "取消点赞成功";
                    }
                    System.out.println(temp);
                    break;
                case POST_COMMENT:
                    System.out.println("发表评论是否成功：" + ((CommentResponse) result).getMessage());
                    break;
                case CREATE_MIX_MOMENT:
                case CREATE_PIC_MOMENT:
                case CREATE_WORD_MOMENT:
                    LoadDialog.dismiss(mContext);
                    System.out.println("发布邻里圈的id为:"+((CreateMomentResponse)result).getResult().getId());
                    break;
                case GET_QI_NIU_TOKEN:
                    QiNiuTokenResponse response3 = (QiNiuTokenResponse) result;
                    if (response3.getCode() == 200) {
                        uploadImage(response3.getResult().getDomain(), response3.getResult().getToken(), selectUri);
                    }
                    break;


            }

        }

        super.onSuccess(requestCode, result);
    }
    @Override
    public void onFailure(int requestCode, int state, Object result) {
        switch (requestCode) {
            case GET_QI_NIU_TOKEN:
                NToast.shortToast(mContext, "发送图片邻里圈失败");
                LoadDialog.dismiss(mContext);
                break;
        }
    }

    /**
     * 测试专用，
     * @param v
     */
    public void doSomething(View v) {
        switch (v.getId()){
            case R.id.btn_sendMixMoment:
                System.out.println("btn_sendMixMoment");
                showPhotoDialog();
//                request(CREATE_MIX_MOMENT,true);
                break;
            case R.id.btn_sendWordMoment:
                System.out.println("btn_sendWordMoment");
                //发一条文字邻里圈
                request(CREATE_WORD_MOMENT,true);
                break;
            case R.id.btn_sendPicMoment:
                System.out.println("btn_sendPicMoment");
                request(CREATE_PIC_MOMENT,true);
                break;
            default:


        }
    }
    /**
     * 弹出底部框
     */
    @TargetApi(23)
    private void showPhotoDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }

        dialog = new BottomMenuDialog(mContext);
        dialog.setConfirmListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                if (Build.VERSION.SDK_INT >= 23) {
                    int checkPermission = checkSelfPermission(Manifest.permission.CAMERA);
                    if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                        if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
                            requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_ASK_PERMISSIONS);
                        } else {
                            new AlertDialog.Builder(mContext)
                                    .setMessage("您需要在设置里打开相机权限。")
                                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_ASK_PERMISSIONS);
                                        }
                                    })
                                    .setNegativeButton("取消", null)
                                    .create().show();
                        }
                        return;
                    }
                }
                photoUtils.takePicture(NeighborhoodActivity.this);
            }
        });
        dialog.setMiddleListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                photoUtils.selectPicture(NeighborhoodActivity.this);
            }
        });
        dialog.show();
    }
    public void uploadImage(final String domain, String imageToken, Uri imagePath) {
        if (TextUtils.isEmpty(domain) && TextUtils.isEmpty(imageToken) && TextUtils.isEmpty(imagePath.toString())) {
            throw new RuntimeException("upload parameter is null!");
        }
        File imageFile = new File(imagePath.getPath());

        if (this.uploadManager == null) {
            this.uploadManager = new UploadManager();
        }
        this.uploadManager.put(imageFile, null, imageToken, new UpCompletionHandler() {

            @Override
            public void complete(String s, ResponseInfo responseInfo, JSONObject jsonObject) {
                if (responseInfo.isOK()) {
                    try {
                        String key = (String) jsonObject.get("key");
                        imageUrl = "http://" + domain + "/" + key;
                        System.out.println("imageUrl is "+imageUrl);
                        picList.add(imageUrl);
                        Log.e("uploadImage", imageUrl);
                        if (picList.size()>0) {
                            request(CREATE_MIX_MOMENT);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    NToast.shortToast(mContext, getString(R.string.upload_portrait_failed));
                    LoadDialog.dismiss(mContext);
                }
            }
        }, null);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PhotoUtils.INTENT_CROP:
            case PhotoUtils.INTENT_TAKE:
            case PhotoUtils.INTENT_SELECT:
                photoUtils.onActivityResult(NeighborhoodActivity.this, requestCode, resultCode, data);
                break;
        }
    }
}
